﻿using FreesenseSubAIS.Core;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FreesenseSubAIS.Core
{
    /// <summary>
    /// CameraLink相机采集卡相机
    /// </summary>
    internal class CameraVirtual : ICameraAdapter
    {
        private double _exporsetime;
        private List<Tuple<int, string>> cmdList;
        private string _foldername;
        public string CameraName { get; private set; }

        public bool CameraState { get; private set; }

        public CameraVirtual(string cname, string foldername)
        {
            CameraName = cname;
            _foldername = foldername;
            cmdList = new List<Tuple<int, string>>();
        }

        public bool SetExprosetime(double extime)
        {
            if (!CameraState || !(extime > 14) || !(extime < 7000000)) return false;
            _exporsetime = extime;
            return true;
        }

        public bool OneShot()
        {

            return true;
        }

        public bool ContinueShot()
        {
            bool flag = false;
            return flag;
        }

        public bool StopShot()
        {
            bool flag = false;
            return flag;
        }

        public bool Close()
        {
            bool flag = false;
            cmdList.Clear();
            return flag;
        }

        public double GetExprosetime()
        {
            return _exporsetime;
        }

        public double GetErrorCount()
        {
            double errorcount = 0;
            return errorcount;
        }

        public event EventHandler<Bitmap> ImageReady;

        public async Task Init()
        {
            try
            {
                await Task.Run(() => Processfolder(_foldername));
                CameraState = true;
            }
            catch (Exception ex)
            {
                CameraState = false;
                throw new ArgumentException(ex.ToString());
            }
            await Task.Delay(100);
        }

        private void _camera_FrameReady(Bitmap bitmap)
        {
            if (ImageReady != null)
                ImageReady(CameraName, bitmap);
        }

        public bool AquireBitmap()
        {
            return OneShot();
        }

        public bool AquireBitmap(string mapname)
        {
            return OneShot();
        }
        /// <summary>
        /// 按索引号读出图片
        /// </summary>
        /// <param name="mapindex"></param>
        /// <returns></returns>
        public bool AquireBitmap(int mapindex)
        {
            try
            {
                var index = cmdList.FindIndex(x => x.Item1 == mapindex);
                if (index < 0) return false;
                var map = new Bitmap(cmdList[index].Item2);
                _camera_FrameReady(map);
                map.Dispose();
                Console.WriteLine(string.Format("虚拟相机取出{0}图片", mapindex));
            }
            catch
            {
                // ignored
            }
            return true;
        }
        private void Processfolder(string path)
        {
            var list = GetMapNamelist(path);
            if (list == null || list.Count <= 0) return;
            {
                var selpic = Device.defaultProduct.ParamList.Where(x => list.Any(y => y.Contains(x.PicParameter.Picname))).Select(y => y.PicParameter.Picname).ToList();
                if (isValid(selpic))
                {
                    list.Sort(delegate (string p1, string p2)
                    {
                        var ind = Device.defaultProduct.ParamList.FindIndex(x => p1.Contains(x.PicParameter.Picname));
                        var ind2 = Device.defaultProduct.ParamList.FindIndex(x => p2.Contains(x.PicParameter.Picname));
                        return ind - ind2;
                    });
                    var templist = list.Select(x => string.Format("{0}\\{1}", path, x)).ToList();
                    cmdList = GetBitmaplist(templist);
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("必须含有校正、上清灰、下清灰图，请重新选择文件夹");
                }
            }
        }
        private List<Tuple<int, string>> GetBitmaplist(List<string> bitmapfilename)
        {
            List<Tuple<int, string>> tempbitmap = new List<Tuple<int, string>>();
            var indexlist = Device.defaultProduct.ParamList.Select(x => x.PicParameter.Picindex).ToList();
            for (int i = 0; i < bitmapfilename.Count && i < indexlist.Count; i++)
            {
                var picname = Device.defaultProduct.ParamList.Find(x => x.PicParameter.Picindex == indexlist[i]).PicParameter.Picname;
                var mapindex = bitmapfilename.FindIndex(x => x.Contains(picname));
                if (mapindex > -1)
                    tempbitmap.Add(new Tuple<int, string>(indexlist[i], bitmapfilename[mapindex]));
            }
            return tempbitmap;
        }
        private bool isValid(List<string> list)
        {
            List<int> stand = new List<int> { -3, -2 };
            if (list == null || list.Count == 0)
                return false;
            var indexlist = Device.defaultProduct.ParamList.Where(x => list.Contains(x.PicParameter.Picname)).Select(x => x.PicParameter.Picindex).ToList();
            var temp = indexlist.Intersect(stand).ToList();
            if (temp.Any())
            {
                return true;
            }
            else
                return false;
        }
        private List<string> GetMapNamelist(string path)
        {
            if (Directory.Exists(path))
            {
                string[] productList = Directory.GetFiles(path);
                List<string> ls = new List<string>();
                foreach (string pa in productList)
                {
                    ls.Add(Path.GetFileName(pa));
                }
                return ls;
            }
            else
            {
                Directory.CreateDirectory(path);
                return null;
            }
        }
    }
}
